package gui;

import gui.events.DatabasePopupEvent;
import gui.interfaces.IPopupMenuDatabaseEventListener;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;

public class PopupMenuDatabase extends JPopupMenu {
	private List _listener = new ArrayList();

	/**
	 * Constructor
	 */
	public PopupMenuDatabase() {
		JMenuItem setAsDefault = new JMenuItem("Set as default database");
		setAsDefault.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				fireSetAsDefaultDatabase();
			}
		});
		JMenuItem alter = new JMenuItem("Alter database");
		alter.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				fireAlterDatabase();
			}
		});
		JMenuItem drop = new JMenuItem("Drop database");
		drop.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				fireDropDatabase();
			}
		});
		JMenuItem refreshAll = new JMenuItem("Refresh all");
		refreshAll.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				fireRefreshAll();
			}
		});

		add(setAsDefault);
		add(alter);
		add(drop);
		add(new JSeparator());
		add(refreshAll);
	}

	public synchronized void addPopupDatabaseEventListener(
			IPopupMenuDatabaseEventListener listener) {
		_listener.add(listener);
	}

	public synchronized void removePopupDatabaseEventListener(
			IPopupMenuDatabaseEventListener listener) {
		_listener.remove(listener);
	}

	public synchronized void fireSetAsDefaultDatabase() {
		DatabasePopupEvent event = new DatabasePopupEvent(this);
		Iterator i = _listener.iterator();
		while (i.hasNext()) {
			((IPopupMenuDatabaseEventListener) i.next())
					.setAsDefaultDatabase(event);
		}
	}

	public synchronized void fireAlterDatabase() {
		DatabasePopupEvent event = new DatabasePopupEvent(this);
		Iterator i = _listener.iterator();
		while (i.hasNext()) {
			((IPopupMenuDatabaseEventListener) i.next()).alterDatabase(event);
		}
	}

	public synchronized void fireDropDatabase() {
		DatabasePopupEvent event = new DatabasePopupEvent(this);
		Iterator i = _listener.iterator();
		while (i.hasNext()) {
			((IPopupMenuDatabaseEventListener) i.next()).dropDatabase(event);
		}
	}

	public synchronized void fireRefreshAll() {
		DatabasePopupEvent event = new DatabasePopupEvent(this);
		Iterator i = _listener.iterator();
		while (i.hasNext()) {
			((IPopupMenuDatabaseEventListener) i.next()).refreshAll(event);
		}
	}
}
